\documentclass{article}
\title{Configuring Applications in .NET}
\author{jfang}
\begin{document}
\maketitle
section{General Application Configuration}
subsection{Introduction}
The .Net Framework provides a very convenient and flexible way to configure applications at run time. Using Configuration files developers and administrators can modify settings for applications without having to recompile the application, avoiding many of the redistribution /re-deployment hassles. For example, if you specify the connection string to be used for database connectivity to an application in the configuration files or an update path for the latest version, you will find configuration files make your application more adaptable. Configuration files contain settings for ASP.Net, built-in remoting channels, assembly binding, custom settings for applications, etc.
\subsection{Configuration Files}
Configuration files are XML files that contain the configuration settings. There are three types of configuration files as described below
\begin{itemize}
\item {\bf Machine configuration file}: The machine.config file contains settings that apply to the entire computer. This file is located in the \% runtime install path\%\textbackslash Config directory. There is only one machine.config file on a computer.
\item {\bf Application Configuration file}: The name of this file depends on the application's host. For ASP.Net applications, this file is called web.config and is located in the bin folder of the application root. An ASP.Net application can contain more than one web.config files at sub-directory level. For applications hosted by the executable host, the config file has the same name as the application , with a .config extension and is located in the same directory as the application. Internet Explorer hosted applications specify the name and location of the config file in a link tag.
\item {\bf Security Configuration file}: These configuration files contain information about the code group hierarchy and permission sets for policy levels. There are three levels of security configuration files : Enterprise policy configuration file (Enterprisesec.config), Machine policy configuration file(Security.config) and User policy configuration file(Security.config). Note that you have to be extra careful while editing these files as changes might corrupt the security configurations. 
\end{itemize}
\subsection{Application-specific Custom Configuration Settings Using AppSettings}
Step 1: Define and Specify:\\\\
Configuration files consists of section declarations and configuration settings. ASP.Net provides a default section ``AppSettings'' in the config file to allow for custom application settings. Shown below is the configuration section declaration for the AppSettings section in machine.config. Add the xml snippet for the configuration setting in the AppSetting node, after the <system.web> node and within the $<$configuration$>$ node in the default web.config that is created by default in an ASP.Net project in Visual Studio:
\begin{verbatim}
<configuration>
<configSections>
<section name="appSettings"
type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, 
Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
</configuration>
\end{verbatim}
XML Listing: Section of existing machine.config containing the declaration for the AppSettings Section (No changes required - this section is created by default)\\
(The PublicKeyToken value may vary on your machine)\\
Now we define a custom setting in the ASP.Net application's web.config file for the connection string to be used for database connections for our application. We add our custom setting in the AppSettings section. Shown below is the complete web.config after our modification. 
\begin{verbatim}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation 
defaultLanguage="c#"
debug="true"/>
<customErrors 
mode="RemoteOnly" /> 
<authentication mode="Windows" /> 
<trace
enabled="false"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"/>
<sessionState 
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="false" 
timeout="20" />
<globalization 
requestEncoding="utf-8" 
responseEncoding="utf-8" />
</system.web>
<appSettings>
<add key="connstring" value="data source=dbserver;initialcatalog=DevelopmentDB;persist security nfo=False;user id=DBUser;" />
</appSettings>
</configuration>
\end{verbatim}
XML Listing: Modified web.config for adding custom settings in web.config. Add the code in bold to the web.config file created by default in your VS.Net application.\\
Step 2: Retrieve:\\\\
We will now retrieve the configuration value at run-time the application in order to determine the settings to be applied. Following is the code to retrieve the value of the custom setting that was specified in the config file:
\begin{verbatim}
string strConn;
strConn = ConfigurationSettings.AppSettings["connstring"];
try
{
sqlConnection1.ConnectionString = strConn;
sqlConnection1.Open();
...
...
...
\end{verbatim}
We need to import the namespace System.Configuration for this example. To retrieve the value of a configuration setting in the AppSettings section, we need a single line of code. The ``ConfigurationSettings'' object's static property ``AppSettings'' points to a NameValueCollection object which is indexed on the key name of the configuration.\\
In this article, we will focus on including custom settings in our machine.config or web.config configuration file.
subsecion{Custom Sections in the web.config file}
You are not restricted to using the predefined AppSettings section. Instead of using AppSettings, you can define your custom configuration section in the web.config file. 

Declaring a section defines a new element in the configuration file. 

Step 1: Define a Custom Section in the web.config file and specify the values within the newly defined section:
\begin{verbatim}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="MyAppSection"
type="System.Configuration.SingleTagSectionHandler,system, Version=1.0.3300.0, 
Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<system.web>
<compilation 
defaultLanguage="c#"
debug="true"/>
<customErrors mode="RemoteOnly" /> 
<authentication mode="Windows" /> 
<trace
enabled="false"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"/>
<sessionState 
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="false" 
timeout="20" />
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
</system.web>
<appSettings>
<add key="connstring" value="data source=dbserver;initialcatalog=DevelopmentDB;persist security info=False;user id=DBUser;" />
</appSettings>
<MyAppSection ListLimit="1000" TableLimit="500" PageLimit="10" />
</configuration>
\end{verbatim}
XML Listing: Modified web.config for adding custom sections in web.config

The section declaration contains the section name and type. The section can be of type "SingleTagSectionHandler", "NameValueSectionHandler" or "DictionarySectionHandler". We will explore these different types a little later in this article.

The configSections node in the web.config XML configuration file listed above defines a custom configuration section called "MyAppSection". The PublicKeyToken varies on different machine and the best way to get the appropriate value is by searching in the existing machine.config file for a similar section handler. In this case, we can lookup the PublicKeyToken for an existing section of type SingleTagSectionHandler.

Step 2: Retrieve the configuration values in the application at run time.

...
...
IDictionary sampleTable = (IDictionary) 
ConfigurationSettings.GetConfig("MyAppSection");
string strValue1 = (string)sampleTable["ListLimit"];
string strValue2 = (string)sampleTable["TableLimit"];
string strValue3 = (string)sampleTable["PageLimit"];
...
...

Code Snippet : Retrieve values from custom section from web.config

The ConfigurationSettings object's static method "GetConfig" is used to retrieve the values of the custom section, which are typecast to the appropriate Collection class based on the configuration section declaration.

The child attributes and nodes you define depend on the Section Handler you use for the setting. Sections that are defined using the SingleTagSectionHandler class specify the configuration settings as key value pairs using XML Attributes. Section declarations using the NameValueSectionHandler class allow the configuration information to be specified as name value pairs in XML nodes. The DictionarySectionHandler is similar to the NameValueSectionHandler in storing the configuration information in the xml config file but returns the configuration information as a Dictionary object.

Shown below is the code xml snippet to define and specify a custom section using DictionarySectionHandler class

<P><FONT 
face="Verdana, Arial, Helvetica, sans-serif"><configuration><BR><configSections><BR><section name="dictAppUpdate"<BR>type="System.Configuration.DictionarySectionHandler,system, 
Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null"/><BR></configSections><BR>...<BR><dictAppUpdate><BR><add 
key="updatePath" 
value="f:\\"/><BR></dictAppUpdate><BR>..<BR></configuration></FONT></P>

XML Listing: Adding custom sections in web.config using DictionarySectionHandler class



<FONT face="Verdana, Arial, Helvetica, sans-serif">IDictionary sampleTable = 
(IDictionary) <BR>ConfigurationSettings.GetConfig("dictAppUpdate");<BR>string 
strPath = (string)sampleTable["updatePath"];

Code Lising : Retrieve the Value of the custom section defined using DictionarySectionHandler

We will view an example of a section defined using the NameValueSectionHandler class in the next part of the article. 


\section{Introducing the custom configuration section concept}
\subsection{Introduction}
The custom sections are customized sections that a developer configures by him self. In this case, the developer sets, also, their attributes and elements to suit special applications needs in term of settings. This kind of sections are located always at the top of the configuration files before all others settings. They are wrapped in ``$<$configSections$>$ $<$/configSections$>$'' tags. Those kinds of setting are very useful, especially in the case where customized or specifics settings are required to be set and the use cases according to them are so numerous that one can not enumerate them at all. These kinds of sections have some child elements which are shown in the below given table\\
The section and the section Group tags need further clarifications about how to define and use them. Therefore, I'll take them one by one and I explain the meaning of each one:
\subsection{Section}
The section ties a configuration section handler to a configuration section element. In this context, the configuration section handler is a class like SingleTagSectionHandler, ApplicationSettingGroup, SystemWebSectionGroup, AuthentificationSection and others that handle sections' elements, furthermore, you can even create your own configuration section handler. This concept is applied in the both development contexts. I mean the web application  and the windows or client application context. It takes some arguments that I will indicate where each of them should be used either in a web application configuration context or in a windows application  configuration context.\\
\subsubsection{Used in both contexts:}
\begin{itemize}
\item name: The name of the corresponding section 
\item type: It is composed by five elements, the first one represents the class that handles the given section, and it must be a fully qualified class name like ``System.Web.Configuration.ConfigurationSection'', the second one represents the corresponding assembly name like ``System. Configuration'', the third element is the version such 1.0.0.0, the forth one is dedicated to precise the culture like ``en-US'' or ``en-UK'' witch represents the (language /Region) couple, if no culture have been set, set its value as neutral. And of Corse, the fifth element is the Public key token, this attribute is used for encryption issues, it can have null value if there is not need to use.
\end{itemize}

\end{document}
